﻿using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CNKI.TPI.Web.Base
{
    public class SessionManager
    {
        private static DataTable dt = InitTable();
        private static int timeout = ConfigHelper.GetWebApiLoginSessionTimeout();

        private static DataTable InitTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UserID", typeof(string));
            dt.Columns.Add("UserCode", typeof(string));
            dt.Columns.Add("SessionId", typeof(string));
            dt.Columns.Add("Expired", typeof(DateTime));
            return dt;
        }

        public static string Login(string userid, string usercode)
        {
            string result = "";
            DataRow[] drList = null;
            lock (dt)
            {
                drList = dt.Select("UserID = '" + userid + "' and UserCode = '" + usercode + "'");

                if (drList.Count() == 0)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = userid;
                    dr[1] = usercode;
                    dr[2] = Guid.NewGuid();
                    dr[3] = DateTime.Now.AddSeconds(timeout);
                    result = dr[2].ToString();
                    dt.Rows.Add(dr);
                }
                else
                {
                    if ((DateTime)drList[0][3] >= DateTime.Now)
                    {
                        result = drList[0][2].ToString();
                        drList[0][3] = DateTime.Now.AddSeconds(timeout);
                    }
                    else
                    {
                        drList[0][2] = Guid.NewGuid();
                        drList[0][3] = DateTime.Now.AddSeconds(timeout);
                        result = drList[0][2].ToString();
                    }
                }
            }
            return result;
        }

        public static LoginUserInfo GetUserInfo(string sessionId)
        {
            LoginUserInfo userInfo = null;
            lock (dt)
            {
                DataRow[] drList = dt.Select("SessionId = '" + sessionId + "'");
                if (drList.Count() > 0 && (DateTime)drList[0][3] >= DateTime.Now)
                {
                    userInfo = new LoginUserInfo();
                    userInfo.UserID = drList[0][0].ToString();
                    userInfo.UserCode = drList[0][1].ToString();
                    userInfo.DBInfo = null;
                    drList[0][3] = DateTime.Now.AddSeconds(timeout);
                }
            }
            return userInfo;
        }

    }
}
